package com.hontech.bv.http

import com.hontech.bv.utils.API_BASE_URL
import com.hontech.bv.utils.parseJson
import kotlinx.coroutines.CompletableDeferred
import kotlinx.serialization.SerialName
import okhttp3.*
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import java.util.concurrent.TimeUnit

object Http {

    const val HEAD_RESP = "resp"
    const val RESP_OK = "OK"
    const val RESP_FAIL = "FAIL"

    private val client = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .build()

    suspend fun get(url: String): ByteArray {
        val req = Request.Builder()
            .url("${API_BASE_URL}$url")
            .get()
            .build()
        val promise = CompletableDeferred<ByteArray>()
        val call = client.newCall(req)
        call.enqueue(RespCallback(promise))
        return promise.await()
    }

    suspend fun post(url: String, data: ByteArray): ByteArray {
        val req = Request.Builder()
            .url(url)
            .post(data.toRequestBody())
            .build()
        val promise = CompletableDeferred<ByteArray>()
        val call = client.newCall(req)
        call.enqueue(RespCallback(promise))
        return promise.await()
    }
}

